#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

#define THREAD_COUNT 20000

//初始化互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *thread_func(void *arg)
{

    
    int *p = (int *)arg;
    //加锁
    pthread_mutex_lock(&mutex);
    *p += 1;
    //解锁
    pthread_mutex_unlock(&mutex);
}

int main(int argc, char const *argv[])
{
    int sum = 0;
    //创建线程
    pthread_t tid[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_create(&tid[i], NULL, thread_func, &sum);
    }

    //等待线程结束
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_join(tid[i], NULL);
    }

    printf("sum = %d\n", sum);
    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
    return 0;
}
